package image_api

import (
	"blogx_server/common/res"
	"blogx_server/global"
	"blogx_server/models"
	"blogx_server/service/log_service"
	"blogx_server/utils"
	"blogx_server/utils/file"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"io"
)

func (ImageApi) ImageUploadView(c *gin.Context) {
	fileHeader, err := c.FormFile("file")
	if err != nil {
		res.FailWithError(err, c)
		return
	}
	fmt.Println(fileHeader.Size, "1")
	//文件大小判断
	s := global.Config.Upload.Size
	if fileHeader.Size > s*1024*1024 {
		res.FailWithMsg(fmt.Sprintf("%s图片大小大于2MB", fileHeader.Filename), c)
		return
	}
	//后缀判断
	filename := fileHeader.Filename
	suffix, err := file.ImageSuffixJudge(filename)
	if err != nil {
		res.FailWithError(err, c)
		return
	}
	//文件hash
	file, err := fileHeader.Open()
	if err != nil {
		res.FailWithError(err, c)
		return
	}

	byteData, err := io.ReadAll(file)
	hash := utils.MD5(byteData)

	filePath := fmt.Sprintf("uploads/%s/%s.%s", global.Config.Upload.UploadDir, hash, suffix)

	//判断hash是否存在库中
	var model models.ImageModel

	err = global.DB.Take(&model, "hash = ?", hash).Error
	if err == nil { //没有错误 => 找到图片
		logrus.Infof("图片%s_%s重复上传", model.Filename, model.Hash)
		res.Ok(model.WebPath(), "图片上传成功", c)
		return
	}

	//七牛云接入 TODO
	//qiniu_service.SendReader(fileHeader)

	//入库
	model = models.ImageModel{
		Filename: filename,
		Path:     filePath,
		Size:     fileHeader.Size,
		Hash:     hash,
	}
	err = global.DB.Create(&model).Error
	if err != nil {
		res.FailWithError(err, c)
		return
	}

	err = c.SaveUploadedFile(fileHeader, filePath)
	if err != nil {
		logrus.Errorf("文件保存失败 %s", err)
		res.FailWithError(err, c)
		return
	}
	res.Ok(model.WebPath(), "图片上传成功", c)
}

func (ImageApi) ImageRemoveView(c *gin.Context) {
	var cr models.RemoveRequest
	err := c.ShouldBindJSON(&cr)
	if err != nil {
		res.FailWithError(err, c)
		return
	}
	log := log_service.GetLog(c)
	log.ShowRequest()
	log.ShowResponse()
	var list []models.ImageModel

	global.DB.Find(&list, cr.IDList)

	var successCount, failCount int64
	if len(list) > 0 {
		successCount = global.DB.Delete(&list).RowsAffected
	}
	failCount = int64(len(list)) - successCount
	msg := fmt.Sprintf("操作成功，成功 %d 失败 %d", successCount, failCount)
	res.OkWithMsg(msg, c)
}
